package main

import (
	"context"
	"fmt"
	stream "go_final/demos/grpc_stream/myproto"
	"sync"
	"time"

	"google.golang.org/grpc"
)

func main() {
	conn, err := grpc.Dial(":50052", grpc.WithInsecure())
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	client := stream.NewGreaterClient(conn)

	// 服务端流模式
	res, _ := client.GetStream(context.Background(), &stream.GetStreamRequest{
		Data: "invoke",
	})
	for {
		a, err := res.Recv()
		if err != nil {
			fmt.Println("err: ", err)
			break
		}
		fmt.Println("a: ", a)
	}

	// 客户端流模式
	putS, _ := client.PostStream(context.Background())
	i := 0
	for {
		i++
		putS.Send(&stream.GetStreamRequest{
			Data: fmt.Sprintf("This is the No: %d message.proto from client", i),
		})

		time.Sleep(time.Second)
		if i > 10 {
			break
		}
	}

	// 双向流模式
	allStr, _ := client.AllStream(context.Background())
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		defer wg.Done()
		for {
			data, _ := allStr.Recv()
			println("Get message.proto forms server: ", data.Data)
		}
	}()

	go func() {
		defer wg.Done()
		i := 0
		for {
			i++
			allStr.Send(&stream.GetStreamRequest{
				Data: fmt.Sprintf("This is the No: %d message.proto from client", i),
			})
			time.Sleep(time.Second)
		}
	}()
	wg.Wait()
}
